<?php
/**
 * Created by PhpStorm.
 * User: xudongsheng
 * Date: 2017/9/27
 * Time: 下午1:43
 */

namespace app\admin\controller;


use app\admin\model\Admin;
use app\admin\model\AuthGroup;
use app\admin\model\AuthRule;
use Auth\Auth;
use Category\Category;
use think\Request;

class Sysadmin extends Common
{
    /** 管理员 列表
     * @return mixed
     */
    public function adminList(){
        $userList   =   Admin::all([],'auth_group');
        foreach ($userList as &$v){
            $tmp = [];
            foreach ($v->auth_group as $l){
                $tmp[]  =   $l->title;
            }
            if ($v->admin_id === config('superSysAdmin')){
                $tmp[]  =   '超级系统管理员';
            }
            $v->auth_group = implode(',',$tmp);
        }
        $this->assign('userList',$userList);
        return $this->fetch();
    }

    /** 创建 管理员
     * @param Request $request
     * @return mixed
     */
    public function createAdmin(Request $request){
        $request->isPost() AND $this->createAdminSave();
        //查 所有的 用户组
        $this->assign('auth_group',AuthGroup::field('auth_group_id,title')->where(['status'=>1])->select());
        return $this->fetch();
    }

    /**
     *  创建 管理员 之 保存
     */
    private function createAdminSave(){
        $data   =   input('post.');
        if (($errormsg = $this->validate($data,'admin.create')) !== true){
            $this->error($errormsg);
        }
        $data  ['encrypt']  =   random_str();
        $data  ['password'] = md5($data['encrypt'].$data['password']);
        if ($current = Admin::create($data,true)){
            if (!empty($data['auth_group_id'])){
                $current->authGroup()->attach($data['auth_group_id']);
            }
            $this->success('新增成功！',url('adminList'));
        }
        $this->error('添加失败！');
    }


    public function editAdmin(Request $request,$admin_id){
        ($user  = Admin::get($admin_id,'auth_group')) OR $this->error('此用户不存在！');
        $request->isPost() AND $this->updateAdmin($user);
        //查 所有的 用户组
        $this->assign('auth_group',AuthGroup::field('auth_group_id,title')->where(['status'=>1])->select());
        $this->assign('user',$user);
        $group_id   =   [];
        foreach ($user->auth_group as $v){
            $group_id[] =   $v->auth_group_id;
        }
        $this->assign('group_id',$group_id);
        return $this->fetch();
    }


    private function updateAdmin($user){
        $data   =   input('post.');
        if (($errormsg = $this->validate($data,'admin.edit')) !== true){
            $this->error($errormsg);
        }
        if (!empty($data['password'])){
            if (($errormsg = $this->validate($data,'admin.password')) !== true){
                $this->error($errormsg);
            }
            $user->password =  md5($user->encrypt.$data['password']);
        }
        $user->username =   $data['username'];
        $user->email    =   $data['email'];
        $group_result   =   FALSE;
        if (!empty($data['auth_group_id'])){
            $group_result   = $user->authGroup()->attach($data['auth_group_id']);
        }else{
            $group_result   = $user->authGroup()->detach();
        }
        if ($user->allowField(true)->save() OR is_null($group_result) OR $group_result){
            $this->success('更新成功！',url('adminList'));
        }
        $this->error('更新失败！');

    }


    public function deleteAdmin($admin_id){
        ($admin = Admin::get($admin_id)) OR $this->error('此用户不存在！');
        if ($admin->delete()){
            $admin->auth_group()->detach();
            $this->success('删除成功！',url('adminList'));
        }
        $this->error('删除失败！');
    }

    /** 权限列表
     * @return mixed
     */
    public function auth_rule(){
        $ruleList   =   Category::toLevelTree(AuthRule::all(),0,'auth_rule_id');
        $this->assign('ruleList',$ruleList);
        return $this->fetch();
    }

    /** 新增权限
     * @param Request $request
     * @return mixed
     */
    public function createRule(Request $request,$auth_rule_id = NULL){
//        !$auth_rule_id?AuthRule::get($auth_rule_id)
         if (!is_null($auth_rule_id)){
             AuthRule::get($auth_rule_id) OR $this->error('不存在此权限！');
         }
        $request->isPost() AND $this->createRuleSave();
        $ruleList   =   Category::toLevelTree(AuthRule::all(),0,'auth_rule_id');
        $this->assign('ruleList',$ruleList);
        $this->assign('auth_rule_id',is_null($auth_rule_id)?0:$auth_rule_id);
        return $this->fetch();
    }

    /**
     * 新增权限 保存
     */
    private function createRuleSave(){
        //表单验证
        $data   =   input('post.');
        //检查 是不是 真实有效的 控制器方法
        AuthRule::checkExistence($data['name']) OR $this->error('填写的此权限在系统中不存在！');
        // 如果要求 可以查 唯一
        if (AuthRule::create($data,true)){
            $this->success('增加权限成功！',url('Sysadmin/auth_rule'));
        }
        $this->error('增加权限失败！');
    }

    /** 编辑权限
     * @param Request $request
     * @param $auth_rule_id
     * @return mixed
     */
    public function editRule(Request $request,$auth_rule_id){
        ($auth_rule =    AuthRule::get($auth_rule_id)) OR $this->error('无此权限节点,无法编辑！');
        $request->isPost() AND $this->updateRule($auth_rule);
        $ruleList   =   Category::toLevelTree(AuthRule::all(),0,'auth_rule_id');
        $this->assign('ruleList',$ruleList);
        $this->assign('auth_rule',$auth_rule);
        $this->assign('childId',Category::getChildsId($ruleList,$auth_rule_id,true,'auth_rule_id'));
        return $this->fetch();
    }

    /** 编辑权限 之  保存
     * @param $auth_rule
     */
    private function updateRule($auth_rule){
        //表单验证
        $data   =   input('post.');
        //检查 是不是 真实有效的 控制器方法
        AuthRule::checkExistence($data['name']) OR $this->error('填写的此权限在系统中不存在！');
        if ($auth_rule->isUpdate()->allowField(true)->save($data)){
            $this->success('更新成功！',url('Sysadmin/auth_rule'));
        }
        $this->error('更新失败！');
    }

    /** 删除权限  包含 所有子节点的
     * @param $auth_rule_id
     */
    public function deleteRule($auth_rule_id){
        $rule = AuthRule::all();
        $childId  = Category::getChildsId($rule,$auth_rule_id,true,'auth_rule_id');
        if (AuthRule::destroy($childId)){
            $this->success('删除成功！',url('auth_rule'));
        }
        $this->error('删除失败！');

    }

    /** 用户组 列表
     * @return mixed
     */
    public function auth_group(){
        $this->assign('groups',AuthGroup::field('auth_group_id,title,status')->select());
        return $this->fetch();
    }

    /** 新建 用户组
     * @param Request $request
     * @return mixed
     */
    public function createGroup(Request $request){
        $request->isPost() AND $this->createGroupSave();
        return $this->fetch();
    }

    /**
     * 新建 用户组 之 存储
     */
    private function createGroupSave(){
        if (AuthGroup::create(input('post.'),true)){
            $this->success('增加用户组成功！',url('Sysadmin/auth_group'));
        }
        $this->error('增加用户组失败！');
    }

    /** 编辑 用户组
     * @param Request $request
     * @param $auth_group_id
     * @return mixed
     */
    public function editGroup(Request $request,$auth_group_id){
        ($auth_group =   AuthGroup::get($auth_group_id)) OR $this->error('无此用户组,无法编辑！');
        $request->isPost() AND $this->updateGroup($auth_group);
        $this->assign('auth_group',$auth_group);
        return $this->fetch();
    }

    /** 编辑 用户组 之 保存
     * @param $auth_group
     */
    private function updateGroup($auth_group){
        if ($auth_group->isUpdate()->allowField(true)->save(input('post.'))){
            $this->success('更新成功！',url('Sysadmin/auth_group'));
        }
        $this->error('更新失败！');
    }

    /** 给 角色分配 权限
     * @param Request $request
     * @param $auth_group_id
     * @return mixed
     */
    public function groupAllotRule(Request $request,$auth_group_id){
        ($auth_group =   AuthGroup::get($auth_group_id)) OR $this->error('无此用户组,无法分配！');
        $request->isPost() AND $this->groupAllotRuleSave($auth_group);
        $group_rules = explode(',',$auth_group->rules);
        $this->assign('group_rules',$group_rules);
        $this->assign('auth_group',$auth_group);
        $ruleList   =   Category::toLevelTree(AuthRule::all(['status'=>1]),0,'auth_rule_id');
        $this->assign('ruleList',$ruleList);
        return $this->fetch();
    }

    /**  给 角色分配 权限
     * @param $auth_group
     */
    private function groupAllotRuleSave($auth_group){
        $rules  =   input('post.rules/a');
        $auth_group->rules  =  empty($rules)?'':implode(',',$rules);
        if ($auth_group->save()){
            $this->success('分配成功！',url('Sysadmin/auth_group'));
        }
        $this->error('分配失败！');
    }










}